package com.common.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;

public class MemoryCache <K, V> {

	private Cache cache;
	
	public MemoryCache() {
		try {
			Map<Object, Object> properties = new HashMap<Object, Object>();
			properties.put(GCacheFactory.EXPIRATION_DELTA, 0);
			properties.put(MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT, true);
			
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(properties);
		} catch (CacheException e) {
			//TODO Medium priority: implement the Cache errors
			e.printStackTrace();
		}
	}
	
	public void put(K key, V value) {
		cache.put(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public V get(K key) {
		return (V) cache.get(key);
	}
	
	public boolean containsKey(K key) {
		return cache.containsKey(key);
	}
	
	public boolean containtValue(V value) {
		return cache.containsValue(value);
	}
	
	@SuppressWarnings("unchecked")
	public Map<K, V> getAll(List<K> values) {
		try {
			return cache.getAll(values);
		} catch (CacheException e) {
			e.printStackTrace();
			return new HashMap<K, V>();
		}
	}
	
	public void remove(V value) {
		cache.remove(value);
	}
	
	public int size() {
		return cache.size();
	}
}
